﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using EOS.IDAL;  //
using EOS.DataModel;  //
using System.Data.Entity;
using System.Data;
using System.Data.SqlClient;
using System.Data.Entity.Core.Objects;

namespace EOS.DAL
{
    public partial class UserInfoRepository : BaseRepository<UserInfo>, IUserInfoRepository
    {
        public void  UpdateUserInfo(List<UserInfo> infoList,ref DbContext db)
        {
            StringBuilder sql = new StringBuilder();
            for (int i = 0; i <= infoList.Count-1; i++)
            {
                UserInfo info = infoList[i];
                sql = new StringBuilder();
                sql.AppendLine("update UserInfo set");
                sql.AppendLine(" UName = '" + info.UName + "'");
                sql.AppendLine(" ,SubTime = '" + info.SubTime + "'");
                sql.AppendLine(" where ID = " + info.ID );
                db.Database.ExecuteSqlCommand(sql.ToString());
            }
        }

        public void ExcuteSql(List<UserInfo> infoList)
        {
            var db = DAL.EFContextFactory.GetCurrentDbContext();
            var connection = db.Database.Connection;
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            var tran = db.Database.Connection.BeginTransaction();
            try
            {
                db.Database.UseTransaction(tran);
                this.UpdateUserInfo(infoList, ref db);
                db.SaveChanges();
                tran.Commit();
            }
            catch (Exception)
            {
                tran.Rollback();
            }
        }

        public void ExcuteProc(UserInfo info)
        {
            var db = DAL.EFContextFactory.GetCurrentDbContext();

            SqlParameter id = new SqlParameter("@id", info.ID);
            SqlParameter uname = new SqlParameter("@uname", "proc");
            SqlParameter count = new SqlParameter("@count", "-1");
            count.Direction = ParameterDirection.Output;
            int count1 = db.Database.ExecuteSqlCommand("exec PROC_UPDATE @id,@uname,@count", id, uname, count);
        }

        public void GetDataByProc(UserInfo info)
        {
            var db = DAL.EFContextFactory.GetCurrentDbContext() as DataModelContainer;
            SqlParameter[] sqlParms = new SqlParameter[1];

            sqlParms[0] = new SqlParameter("@id", info.ID);
            //结果集             
            var result = (from G in db.Database.SqlQuery<UserInfo>("exec PROC_SELECT @id", sqlParms) select G).ToList();
        }
    }
}